const base64 = require('/utils/base64.js')

App({
    onLaunch: function () {
        let date = new Date()
        this.globalData.today = date.getFullYear() + '-' + this.addPreZero(date.getMonth() + 1) + '-' + this.addPreZero(date.getDate())
        const updateManager = wx.getUpdateManager()
        updateManager.onUpdateReady(function () {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success: function (res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            })
        })
        wx.getSystemInfo({
            success: e => {
                this.globalData.qrcode_w = e.windowWidth * 400 / 750
                this.globalData.StatusBar = e.statusBarHeight;
                let capsule = wx.getMenuButtonBoundingClientRect();
                if (capsule) {
                    this.globalData.Custom = capsule;
                    this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
                } else {
                    this.globalData.CustomBar = e.statusBarHeight + 60;
                }
                console.log(this.globalData, e,capsule);
                if (this.compareVersion(e.SDKVersion, '2.9.4') < 0) {
                    console.error('请使用 2.2.3 或以上的基础库以使用云能力')
                    wx.showModal({
                        title: '提示',
                        content: '当前微信版本过低，无法使用该功能，请将微信客户端升级到最新版本后重试。',
                    })
                }
            }
        })
        if (!wx.cloud) {
            return console.error('请使用 2.2.3 或以上的基础库以使用云能力')
        }
        wx.cloud.init({
            traceUser: true,
        })
        this.db = wx.cloud.database()
    },
    globalData: {
        aeskey: "dqzhiyu",
        userInfo: null,
        statusAppointTitle: {
            1: {
                text: '等待抽签',
                color: 'text-orange'
            },
            2: {
                text: '预约成功',
                color: 'text-green'
            },
            3: {
                text: '预约失败',
                color: 'text-red'
            },
            4: {
                text: '已取消',
                color: 'text-grey'
            },
            5: {
                text: '已过期',
                color: 'text-grey'
            },
            6: {
                text: '已失效',
                color: 'text-grey'
            },
            7: {
                text: '已使用',
                color: 'text-brown'
            }
        },
        statusShopTitle: {
            0: {
                text: '待提交',
                color: 'text-black',
                bg: 'black'
            },
            1: {
                text: '等待审核',
                color: 'text-orange',
                bg: 'orange'
            },
            2: {
                text: '审核通过',
                color: 'text-green',
                bg: 'green'
            },
            3: {
                text: '审核失败',
                color: 'text-red',
                bg: 'red'
            },
        },
        statusGroupTitle: {
            1: {
                text: '创始人',
                color: 'text-orange'
            },
            2: {
                text: '管理员',
                color: 'text-green'
            },
            3: {
                text: '已禁用',
                color: 'text-red'
            },
        },
        getUserInfo: false
    },
    //通过此方法获取用户数据
    userInfo(success, fail) {
        //先判断是否有userinfo
        if (this.globalData.userInfo) {
            if (typeof success == 'function') success(this.globalData.userInfo)
            return
        }
        //再判断是否尝试过getUserInfo接口
        if (this.globalData.getUserInfo) {
            if (typeof fail == 'function') fail()
            return
        }
        this.globalData.getUserInfo = true
        //最后尝试userInfo接口
        wx.getUserInfo({
            success: (res) => {
                this.login(res.userInfo, success)
            },
            fail(res) {
                if (typeof fail == 'function') fail()
                return
            }
        })
    },
    login(userInfo, success) {
        wx.cloud.callFunction({
            name: 'login',
            success: res => {
                let openid = res.result.openid
                this.db.collection('user').where({
                    _openid: openid
                }).get().then(res => {
                    if (res.data.length > 0) {
                        //更新数据并登录
                        userInfo.update_time = this.getDatetime(new Date())
                        this.db.collection('user').where({
                            _openid: openid
                        }).update({
                            data: userInfo,
                            success: res1 => {
                                for (let x in userInfo) {
                                    res.data[0][x] = userInfo[x]
                                }

                                this.globalData.userInfo = res.data[0]
                                if (typeof success == 'function') success(res.data[0])
                                return
                            },
                            fail: err => {
                                icon: 'none',
                                console.error('用户更新失败：', err)
                            }
                        })
                    } else {
                        userInfo.create_time = this.getDatetime(new Date())
                        userInfo.update_time = this.getDatetime(new Date())
                        this.db.collection('user').add({
                            data: userInfo
                        }).then(res => {
                            userInfo._openid = openid
                            userInfo._id = res._id
                            this.globalData.userInfo = userInfo
                            if (typeof success == 'function') success(userInfo)
                            return
                        })
                    }
                })
            },
            fail: err => {
                wx.showToast({
                    title: '登录失败，请重试',
                    icon: 'none'
                })

                return
            }
        })
    },
    distance: function (la1, lo1, la2, lo2) {
        var La1 = la1 * Math.PI / 180.0;
        var La2 = la2 * Math.PI / 180.0;
        var La3 = La1 - La2;
        var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
        s = s * 6378.137;
        s = Math.round(s * 10000) / 10000;
        s = s.toFixed(2);
        return s;
    },
    addPreZero: function (num, len = 2) {
        var t = (num + '').length,
            s = '';
        for (var i = 0; i < len - t; i++) {
            s += '0';
        }
        return s + num;
    },
    getDate(date) {
        return date.getFullYear() + '-' + this.addPreZero(date.getMonth() + 1) + '-' + this.addPreZero(date.getDate())
    },
    getDatetime(date) {
        return date.getFullYear() + '-' + this.addPreZero(date.getMonth() + 1) + '-' + this.addPreZero(date.getDate()) + ' ' + this.addPreZero(date.getHours()) + ':' + this.addPreZero(date.getMinutes()) + ':' + this.addPreZero(date.getSeconds())
    },
    compareVersion(v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }

        return 0
    },
    random(len) {
        len = len || 32;
        var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=_';
        var maxPos = $chars.length;
        var pwd = '';
        for (let i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    },
    upload(path, filename, next) {

        let date = new Date()
        filename += '-' + date.getFullYear() + this.addPreZero(date.getMonth() + 1) + this.addPreZero(date.getDate()) + this.addPreZero(date.getHours()) + this.addPreZero(date.getMinutes()) + this.addPreZero(date.getSeconds()) + this.addPreZero(date.getMilliseconds(), 3) + this.addPreZero(parseInt(Math.random() * 9999), 4)

        let ext = path.split('.')
        ext = ext[ext.length - 1]
        filename += '.' + ext
        wx.cloud.uploadFile({
            cloudPath: filename,
            filePath: path,
            success: res => {
                next(res)
            }
        })
    },
    cloud(name, data = {}, success, fail, loading = false, def = false) {

        var that = this
        if (typeof name == 'object') {
            if (name.data != undefined) data = name.data
            if (name.success != undefined) success = name.success
            if (name.fail != undefined) fail = name.fail
            if (name.loading != undefined) loading = name.loading
            if (name.def != undefined) def = name.def
            name = name.name
        }

        if (typeof data != 'object') {
            data = {}
        }
        if (loading) wx.showLoading({
            title: loading,
            mask: true
        })
        wx.cloud.callFunction({
            name: name,
            data: data,
            success: function (res) {
                if (loading) wx.hideLoading()

                if (res.result.code == 200) {
                    console.log('云函数' + name + '请求成功', data, res.result)
                    if (typeof success == "function") success(res.result)
                    else if (def) {
                        if (res.result.msg) {
                            wx.showToast({
                                title: res.result.msg,
                                complete: function () {
                                    if (res.result.url) {
                                        setTimeout(function () {
                                            wx.redirectTo({
                                                url: res.result.url,
                                            })
                                        }, 1500)
                                    }
                                }
                            })
                        } else {
                            if (res.result.url) {
                                wx.redirectTo({
                                    url: res.result.url,
                                })
                            }
                        }
                    }
                } else {
                    console.log('云函数' + name + '请求失败', data, res.result)
                    if (typeof fail == "function") fail(res.result)
                    else if (def) {
                        if (res.result.msg) {
                            wx.showToast({
                                title: res.result.msg,
                                icon: 'none',
                                complete: function () {
                                    if (res.result.url) {
                                        setTimeout(function () {
                                            wx.redirectTo({
                                                url: res.result.url,
                                            })
                                        }, 1500)
                                    }
                                }
                            })
                        } else {
                            if (res.result.data.url) {
                                wx.redirectTo({
                                    url: res.result.data.url,
                                })
                            }
                        }
                    }
                }
            },
            fail: function (res) {
                wx.hideLoading()
                console.log('网络请求失败', name, data, res)
            }
        })
    },
    scancode(shop_id) {
        wx.scanCode({
            success: (res) => {
                console.log(res)
                if (res.errMsg == "scanCode:ok" && res.scanType == "QR_CODE") {
                    let _id = base64.decode(res.result)
                    if (!_id ) {
                        return wx.showToast({
                            title: '二维码不正确',
                            icon: 'none'
                        })
                    }
                    let code = _id.split('|')
                    _id = code[1]
                    if(code[0]=='user'){
                        wx.showLoading({
                            title: '加载中',
                            mask: true
                        })
                        
                        this.db.collection('user').where({
                            _openid: _id
                        }).field({
                            nickName: true,
                            _openid: true
                        }).get({
                            complete: res => {
                                wx.hideLoading()
                            },
                            success: res => {
                                res.data = res.data[0]
                                wx.showModal({
                                    title: '扫描结果',
                                    content: '是否添加' + res.data.nickName + '为员工',
                                    success: rs => {
                                        if (rs.confirm) {
                                            this.cloud({
                                                name: 'shopStaffAdd',
                                                data: {
                                                    shop_id: shop_id,
                                                    _openid: _id
                                                },
                                                def: true,
                                                loading: '提交中',
                                                success: res => {
                                                    wx.showModal({
                                                        title: '操作结果',
                                                        content: '添加成功',
                                                        cancelText: '查看员工',
                                                        success: res => {
                                                            if (res.cancel) {
                                                                wx.navigateTo({
                                                                    url: '/pages/shopStaffs/index?shop_id=' + shop_id,
                                                                })
                                                            }
                                                        }
                                                    })
                                                }
                                            })
                                        }
                                    }
                                })
                            },
                            fail: res => {
                                console.error(res)
                                wx.showToast({
                                    title: '未找到用户',
                                    icon: 'none'
                                })
                            }
                        })
                    }else if(code[0]=='appoint'){
                        wx.navigateTo({
                          url: '/pages/shopAppoint/index?_id='+code[1],
                        })
                    }else{
                        wx.showToast({
                            title: '二维码不正确',
                            icon: 'none'
                        })
                    }
                } else {
                    wx.showToast({
                        title: '无法识别',
                        icon: 'none'
                    })
                }
            },
        })
    },
})